package com.polaris.live.ui.main.live

import android.os.Bundle
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.DisplayUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.databinding.FragmentLiveBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.translation.R
import com.polaris.live.ui.main.fragment.FriendShipFragment
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.interfaces.OnGotoListener
import com.polaris.live.utils.interfaces.OnRefreshStateListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.me.MainLiveViewModel
import com.polaris.live.widget.tab.OnTabSelectListener
import com.polaris.live.widget.tab.TabBean

/**
 * LiveFragment
 *
 * @author Created by 半仙 on 2024/2/27/027 10:19
 */
class LiveFragment : BaseVbFragment<MainLiveViewModel, FragmentLiveBinding>(), OnAutoRefreshListener,
    OnGotoListener, OnRefreshStateListener {

    private val mFragments = ArrayList<Fragment>()

    private val mTitles = ArrayList<TabBean>()

    private lateinit var mTabAdapter: ViewPagerAdapter

    //落地页是否有直播页
    private var mAppPrimaryLive = false

    override fun initView(savedInstanceState: Bundle?) {
        updateImmersionBar()
        initTitle()
        initObserver()
        mBinding.ivSearch.setOnSingleClickListener {
            GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                Router.builder(RoutePath.SEARCH_USER_ACTIVITY).navigation(requireActivity())
            })
        }
    }

    private fun initObserver() {
        mBinding.rank.setOnSingleClickListener {
            GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                if (CommonUtils.isMan(UserManager.getUser().sex)) {
                    Router.builder(RoutePath.USER_RANK_ACTIVITY)
                        .withInt("page", 1)
                        .navigation(requireActivity())
                } else {
                    Router.builder(RoutePath.USER_RANK_ACTIVITY)
                        .withInt("page", 0)
                        .navigation(requireActivity())
                }
            })
        }
    }

    private fun initTitle() {
        val page = DisplayUtil.getSecondaryPagesByPrimaryPage(DisplayUtil.LIVE)
        page?.secondaryPages?.forEach {
            when (it) {
                DisplayUtil.LIVE_LIVE -> {
                    mTitles.add(TabBean(StringUtils.getString(R.string.Live)))
                    mFragments.add(LiveListFragment())
                    mAppPrimaryLive = true
                }

                DisplayUtil.LIVE_PARTY -> {
                    mTitles.add(TabBean(StringUtils.getString(R.string.friend_ship)))
                    mFragments.add(FriendShipFragment())
                }

                DisplayUtil.LIVE_MINE -> {
                    mTitles.add(TabBean(StringUtils.getString(R.string.my_string)))
                    mFragments.add(RoomMeFragment())
                }
                DisplayUtil.LIVE_FOLLOW -> {
                    mTitles.add(TabBean(StringUtils.getString(R.string.following)))
                    mFragments.add(LiveFollowMainFragment())
                }
            }
        }
        mBinding.tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mBinding.pager.currentItem = position
            }

            override fun onTabReselect(position: Int) {
                onAutoRefresh()
            }
        })

        mTabAdapter = ViewPagerAdapter(mFragments, this)
        mBinding.pager.adapter = mTabAdapter
        mBinding.pager.offscreenPageLimit = mFragments.size

        mBinding.tab.setViewPage(mBinding.pager)
        mBinding.tab.setTabs(mTitles, mBinding.svScroll)

        DisplayUtil.getDefaultIndexBySecondaryPrimaryId(
            getGotoDate()?.index,
            DisplayUtil.LIVE,
            page
        )?.also {
            mBinding.tab.onPageSelected(it)
            mBinding.pager.setCurrentItem(it, false)
        }
    }

    override fun onAutoRefresh() {
        if (!isCreated()) {
            return
        }

        val fragment = mFragments.getOrNull(mBinding.pager.currentItem) ?: return
        if (fragment is OnAutoRefreshListener) {
            (fragment as OnAutoRefreshListener).onAutoRefresh()
        }
    }

    override fun onRefreshState() {
        if (isCreated()) {
            val fragment = mFragments.getOrNull(mBinding.pager.currentItem) ?: return
            if (fragment is OnRefreshStateListener) {
                fragment.onRefreshState()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (isCreated()) {
            checkLiveModule()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            checkLiveModule()
            updateImmersionBar()
        }
    }

    private fun checkLiveModule() {

        if (!mAppPrimaryLive) return

        val setting = UserManager.getUser().setting?.liveSwitch
        val indexOfFirst = mFragments.indexOfFirst { it is LiveListFragment }

        if (setting == null || setting.toBoolean()) {
            if (indexOfFirst == -1) {
                mTitles.add(TabBean(StringUtils.getString(R.string.Live)))
                mFragments.add(LiveListFragment())
                mBinding.tab.setTabs(mTitles, mBinding.svScroll)
                mTabAdapter.setFragments(mFragments)
            }
        } else {
            if (indexOfFirst != -1) {
                mFragments.removeAt(indexOfFirst)
                mTitles.removeAt(indexOfFirst)
                mBinding.tab.setTabs(mTitles, mBinding.svScroll)
                mTabAdapter.removeFragment(indexOfFirst)
            }
        }
    }

    private var mGotoData: OnGotoListener.GotoData? = null

    override fun onGoto(gotoData: OnGotoListener.GotoData) {
        if (!isCreated()) {
            mGotoData = gotoData
        } else {
            mBinding.pager.currentItem = gotoData.index
        }
    }

    private fun getGotoDate(): OnGotoListener.GotoData? {
        return if (mGotoData == null) {
            null
        } else {
            mGotoData.apply {
                mGotoData = null
            }
        }
    }

    private fun updateImmersionBar() {
        NavigationBarUtils.setImmersionBarForMain(this, mBinding.llTab)
    }

    companion object {

        const val SUBSIDT_SHOW = 0
        const val SUBSIDY_CLOSE = 1
        const val SUBSIDY_OPEN = 2
    }
}